package initilization

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"handitem/xxb-gin-web/commons/filter"
	"handitem/xxb-gin-web/commons/middle"
	"handitem/xxb-gin-web/global"
	"handitem/xxb-gin-web/router"
	"handitem/xxb-gin-web/router/code"
	"handitem/xxb-gin-web/router/login"
	"handitem/xxb-gin-web/router/sys"
	"net/http"
	"time"
)

func InitGinRouter() *gin.Engine {
	// 创建gin服务
	ginServer := gin.Default()

	//解决前后端跨域问题
	ginServer.Use(filter.Cors())
	// 提供服务组
	//courseRouter := router.RouterWebGroupApp.Course.CourseRouter
	videoRouter := router.RouterWebGroupApp.Video.VideoRouter
	loginApiRouter := login.LoginRouter{}
	codeRouter := code.CodeRouter{}
	logOutRouter := login.LogOutRouter{}
	sysUsersRouter := sys.SysUsersRouter{}
	// 业务模块接口，
	privateGroup := ginServer.Group("api")
	// 接口隔离，比如登录，健康检查都不需要拦截和做任何的处理
	loginApiRouter.InitLoginRouter(privateGroup)
	codeRouter.InitCodeRouter(privateGroup)

	//需要jwt拦截的部分
	privateGroup.Use(middle.JWTAuth())
	{
		sysUsersRouter.InitSysUsersRouter(privateGroup)
		logOutRouter.InitLogOutRouter(privateGroup)
		videoRouter.InitVideoRouter(privateGroup)
		//courseRouter.InitCourseRouter(publicGroup)
	}

	fmt.Println("router register success")
	return ginServer
}

func RunServer() {
	// 初始化路由
	srv := InitGinRouter()
	// 为用户头像和文件提供静态地址
	srv.StaticFS("/static", http.Dir("/static"))
	address := global.Config.Server.Port
	// 启动HTTP服务,courseController
	s := initServer(address, srv)
	// 保证文本顺序输出
	// In order to ensure that the text order output can be deleted
	time.Sleep(10 * time.Microsecond)

	s2 := s.ListenAndServe().Error()
	fmt.Println("服务启动完毕 ", s2)
}
